<?php

declare(strict_types=1);

namespace App\Controller;


use App\Constants\HttpCode;
use App\Model\User;
use App\Request\LoginRequest;
use App\Traits\ApiResponseTrait;
use Hyperf\HttpServer\Contract\RequestInterface;
use HyperfExt\Jwt\Contracts\JwtFactoryInterface;
use Psr\Http\Message\ResponseInterface;

class LoginController extends AbstractController
{
    use ApiResponseTrait;

    /**
     * 登录
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function login(RequestInterface $request)
    {

        $credentials = $request->all();
        if (!$token = auth('api')->attempt($credentials)) {
            return $this->setHttpCode(HttpCode::UNAUTHORIZED)->fail('Unauthorized');
        }
        return $this->respondWithToken($token);
    }

    /**
     * 模拟注册
     * @param LoginRequest $request
     * @return ResponseInterface
     */
    public function reg(LoginRequest $request)
    {
        $model = new User();
        $model->name = $request->input('name');
        $model->password = password_hash($request->input('password'), PASSWORD_BCRYPT);;
        return $this->success($model->save());
    }

    /**
     * @return ResponseInterface
     * 退出登录
     */
    public function logout()
    {
        auth('api')->logout();

        return $this->success('Successfully logged out');
    }

    /**
     * 获取用户信息
     * @return ResponseInterface
     */
    public function me()
    {
        return $this->success(auth('api')->user());
    }

    /**
     * @param $token
     * @return ResponseInterface
     */
    protected function respondWithToken($token): ResponseInterface
    {
        return $this->success([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expire_in' => make(JwtFactoryInterface::class)->make()->getPayloadFactory()->getTtl()
        ]);
    }
}